package com.ruoyi.project.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.juhe.sdk.ApiClient;
import com.juhe.sdk.common.Result;
import com.juhe.sdk.reqeust.GetPersonalHouseResponse;
import com.juhe.sdk.reqeust.PersonalHouseRequest;
import com.juhe.sdk.reqeust.UploadAuthFile64Request;
import com.juhe.sdk.response.FileInfoResponse;
import com.juhe.sdk.response.PersonalHouseResponse;
import com.juhe.sdk.response.PersonalRentApplyResponse;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SMSUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SiyuImmovable;
import com.ruoyi.project.system.domain.SysBlacklist;
import com.ruoyi.project.system.domain.SysQuery;
import com.ruoyi.project.system.domain.vo.Record;
import com.ruoyi.project.system.mapper.SysBlacklistMapper;
import com.ruoyi.project.system.mapper.SysQueryMapper;
import com.ruoyi.project.system.service.ISysQueryService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.file.FileUtils.makeAithFile;

/**
 * 进件记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Slf4j
@Service
public class SysQueryServiceImpl implements ISysQueryService {

    @Autowired
    private SysQueryMapper sysQueryMapper;

    @Autowired
    private SysBlacklistMapper sysBlacklistMapper;

    @Override
    public int addImmovablePropertyQuery(SysQuery sysQuery) {
        // 1.上传授权文件
        Document document = makeAithFile(sysQuery);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.saveToStream(outputStream, FileFormat.PDF);
        document.close();
        String base64EncodedString = Base64.getEncoder().encodeToString(outputStream.toByteArray()).trim();
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "", "");
        UploadAuthFile64Request param = new UploadAuthFile64Request();
        param.setBase64(base64EncodedString);
        param.setFilename("当事人授权书_" + sysQuery.getCardNo() + ".pdf");
        try {
            Result<FileInfoResponse> response = apiClient.uploadAuthFile64(param);
//            Result<FileInfoResponse> response = JSON.parseObject("{\"code\":200,\"data\":{\"fileId\":\"6117351581241344\",\"requestId\":" +
//                    "\"6117351817342976\"},\"msg\":\"成功\"}", Result.class);
            log.warn("---上传授权文件返回---：" + JSON.toJSONString(response));
            if (response.getCode() != 200) {
                log.error("调用出错： {}", JSONObject.toJSONString(response));
                return -1;
            }
            // 2.个人不动产信息
            PersonalHouseRequest param_ = new PersonalHouseRequest();
            param_.setFullName(sysQuery.getName());
            param_.setIdCardNo(sysQuery.getCardNo());
            param_.setFileId(response.getData().getFileId());
//            param_.setFileId("6117351581241344");
            param_.setFileTypes("3");
            Result<PersonalHouseResponse> response_ = apiClient.getPersonalHouse(param_);
//            Result<PersonalHouseResponse> response_ = JSON.parseObject("{\"code\":200,\"data\":{\"messge\":\"查询成功有结果\",\"requestId\"" +
//                    ":\"6117352146153472\",\"resultCode\":1,\"taskId\":\"8d45a999190d4f3a8d0721bfca6b6e73\"},\"msg\":\"成功\"}", Result.class);
            log.warn("---建立查询任务返回---：" + JSON.toJSONString(response_));
            SiyuImmovable immovable = new SiyuImmovable(sysQuery.getId().intValue(), JSON.toJSONString(response), JSON.toJSONString(response_));
            // 3.主要查询信息
            sysQueryMapper.insertSiyuImmovable(immovable);
            // 4.写入记录
            sysQuery.setQueryInfo(immovable.getId().toString());
            sysQueryMapper.updateSysQuery(sysQuery);
            if (response_.getCode() != 200) {
                log.error("调用出错： {}", JSONObject.toJSONString(response_));
            }
            return immovable.getId();
        } catch (Exception e) {
            log.error("调用出错: {}", e);
            return -1;
        }
    }

    @Override
    public AjaxResult immovablePropert(SysQuery sysQuery) {
        AjaxResult result = new AjaxResult();
        Map<String, Object> immovableMap = sysQueryMapper.selectSiyuImmovableByQueryId(sysQuery.getId().intValue());
        result.putAll(immovableMap);
        result.put("success", false);
        // 1. 已发起过历史查询且结果为 审核不通过/审核通过
        if (immovableMap.get("personalRentApply") != null) {
            JSONObject detail = JSON.parseObject(immovableMap.get("personalRentApply").toString()).getJSONObject("data").getJSONObject("detail");
            String approvalStatus = detail.getString("approvalStatus");
            if (!"IN_APPROVAL".equals(approvalStatus)) {
                JSONArray authResults = detail.getJSONArray("authResults");
                boolean isPass = true;
                if (authResults != null) {
                    for (int i = 0; i < authResults.size(); i++) {
                        String authState = authResults.getJSONObject(i).getString("authState");
                        if ("10".equals(authState) || "20".equals(authState)) {
                            isPass = false;
                            break;
                        }
                    }
                }
                if (isPass) {
                    result.replace("success", true);
                    return result;
                }
            }
        }
        // 2. 发起查询
        JSONObject data = JSON.parseObject(immovableMap.get("personalHouse").toString()).getJSONObject("data");
        log.warn("---请求获取不动产(任务编号)---：" + data.getString("requestId"));
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "", "");
        GetPersonalHouseResponse param = new GetPersonalHouseResponse();
        param.setIdCardNo(sysQuery.getCardNo());
        param.setTaskId(data.getString("taskId"));
        try {
            Result<PersonalRentApplyResponse> response = apiClient.getPersonalHouseResponse(param);

//            Result<PersonalRentApplyResponse> response = JSON.parseObject("{\n" +
//                    "    \"code\": 200,\n" +
//                    "    \"data\": {\n" +
//                    "        \"detail\": {\n" +
//                    "            \"approvalStatus\": \"APPROVED\",\n" +
//                    "            \"authResults\": [\n" +
//                    "                {\n" +
//                    "                    \"isReAuth\": \"0\",\n" +
//                    "                    \"cardNum\": \"513721199508103873\",\n" +
//                    "                    \"authState\": \"30\",\n" +
//                    "                    \"authStateDesc\": \"核查成功\",\n" +
//                    "                    \"resultList\": [\n" +
//                    "                        {\n" +
//                    "                            \"certNo\": \"宁（2020）中卫市不动产权第T0003344号\",\n" +
//                    "                            \"unitNo\": \"640502101037GB00010F00270066\",\n" +
//                    "                            \"ownership\": \"共同共有\",\n" +
//                    "                            \"rightsType\": \"国有建设用地使用权/房屋所有权\",\n" +
//                    "                            \"rightsEndTime\": \"2080-08-10\",\n" +
//                    "                            \"useTo\": \"住宅\",\n" +
//                    "                            \"isSealUp\": \"否\",\n" +
//                    "                            \"houseArea\": \"156.29\",\n" +
//                    "                            \"location\": \"沙坡头区迎宾大道东侧宁钢·恒祥国际27#楼1-501\",\n" +
//                    "                            \"isMortgaged\": \"是\",\n" +
//                    "                            \"rightsStartTime\": \"2010-08-10\"\n" +
//                    "                        },\n" +
//                    "                        {\n" +
//                    "                            \"certNo\": \"宁（2018）中卫市不动产权第1402814号\",\n" +
//                    "                            \"unitNo\": \"640502104204JC10009F99990001\",\n" +
//                    "                            \"ownership\": \"共同共有\",\n" +
//                    "                            \"rightsType\": \"宅基地使用权/房屋所有权\",\n" +
//                    "                            \"rightsEndTime\": \"1990-01-01\",\n" +
//                    "                            \"useTo\": \"None\",\n" +
//                    "                            \"isSealUp\": \"否\",\n" +
//                    "                            \"houseArea\": \"80.60\",\n" +
//                    "                            \"location\": \"中卫市沙坡头区镇罗镇镇北村10队\",\n" +
//                    "                            \"isMortgaged\": \"是\",\n" +
//                    "                            \"rightsStartTime\": \"1990-01-01\"\n" +
//                    "                        }\n" +
//                    "                    ]\n" +
//                    "                }\n" +
//                    "            ]\n" +
//                    "        },\n" +
//                    "        \"messge\": \"查询成功\",\n" +
//                    "        \"requestId\": \"6117641243683840\",\n" +
//                    "        \"resultCode\": 1\n" +
//                    "    },\n" +
//                    "    \"msg\": \"成功\"\n" +
//                    "}", Result.class);

            String personalRentApply = JSON.toJSONString(response);
            log.warn("---请求获取不动产返回---：" + personalRentApply);

            Date updateTime = DateUtils.getNowDate();
            sysQueryMapper.updateSiyuImmovablePersonalRentApply((int) immovableMap.get("id"), personalRentApply, updateTime);

            if (response.getCode() == 200) {
                // 即时查询处于审核中
                if ("APPROVED".equals(response.getData().getDetail().getString("approvalStatus"))) {

                    com.alibaba.fastjson.JSONArray authResults = response.getData().getDetail().getJSONArray("authResults");
                    boolean isPass = true;
                    for (int i = 0; i < authResults.size(); i++) {
                        String authState = authResults.getJSONObject(i).getString("authState");
                        if ("10".equals(authState) || "20".equals(authState)) {
                            isPass = false;
                            break;
                        }
                    }
                    if (!isPass) {
                        LocalDateTime createTime = (LocalDateTime) immovableMap.get("createTime");
                        DayOfWeek dayOfWeek = createTime.getDayOfWeek();
                        long daysBetween = ChronoUnit.DAYS.between(createTime, LocalDateTime.now());
                        if (("SATURDAY".equals(dayOfWeek) || "SUNDAY".equals(dayOfWeek)) && daysBetween < 3) {
                            // T+3
                            result.put("time", createTime.plusDays(3));
                            return result;
                        } else if (createTime.getHour() < 17) {
                            // T+1
                            if (daysBetween < 1) {
                                result.put("time", createTime.plusDays(1));
                                return result;
                            }
                        } else {
                            // T+2
                            if (daysBetween < 2) {
                                result.put("time", createTime.plusDays(2));
                                return result;
                            }
                        }
                    }
                } else {
                    result.put("personalRentApply", personalRentApply);
                    result.put("updateTime", updateTime);
                    return result;
                }
                result.put("success", true);
                result.put("personalRentApply", personalRentApply);
                result.put("updateTime", updateTime);
                return result;
            } else {
                return result;
            }
        } catch (Exception e) {
            log.error("调用出错: {}", e);
            return result;
        }
    }

    @Override
    public AjaxResult judicialQuery(SysQuery sysQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase() + "JF025");
        params.put("inter_id", "JF025");
        params.put("name", sysQuery.getName());
        params.put("cardNo", sysQuery.getCardNo());
        result.put("grss", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        return result;
    }

    @Override
    public AjaxResult bigDataQuery(SysQuery sysQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        params.put("req_time", System.currentTimeMillis());
        params.put("request_sn", "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase() + "JF011");
        params.put("inter_id", "JF011");
        params.put("name", sysQuery.getName());
        params.put("cardNo", sysQuery.getCardNo());
        params.put("mobile", sysQuery.getMobile());
        result.put("dttz", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        return result;
    }

    @Override
    public AjaxResult bigDataQueryPro(SysQuery sysQuery) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        String baseReqSn = "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase();
        params.put("req_time", System.currentTimeMillis());
        // 个人诉讼
        params.put("request_sn", baseReqSn + "JF025");
        params.put("inter_id", "JF025");
        params.put("name", sysQuery.getName());
        params.put("cardNo", sysQuery.getCardNo());
        result.put("grss", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 手机三要素
        params.replace("request_sn", baseReqSn + "JF007");
        params.replace("inter_id", "JF007");
        params.put("mobile", sysQuery.getMobile());
        result.put("sjsys", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 多头
        params.replace("request_sn", baseReqSn + "JF011");
        params.replace("inter_id", "JF011");
        result.put("dttz", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 借选指数
        params.replace("request_sn", baseReqSn + "JF010");
        params.replace("inter_id", "JF010");
        result.put("jxzs", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 特殊名单验证
        String[] labelsList = sysBlacklistMapper.selectLabelsList(new SysBlacklist(sysQuery));
        JSONArray includes = new JSONArray();
        for (String labels : labelsList) {
            JSONArray array = JSON.parseArray(labels);
            for (int i = 0; i < array.size(); i++) {
                String label = array.getString(i);
                if (!includes.contains(label)) {
                    includes.add(label);
                }
            }
        }
        JSONObject labels = new JSONObject();
        labels.put("retcode", "000000");
        labels.put("retdata", includes.toJSONString());
        result.put("labels", labels);
        return result;
    }

    @Override
    public JSONObject companyQuery(SysQuery sysQuery) {
        JSONObject params = new JSONObject();
        String baseReqSn = "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase();
        params.put("req_time", System.currentTimeMillis());
        // 个人诉讼
        params.put("request_sn", baseReqSn + "JF033");
        params.put("inter_id", "JF033");
        params.put("mobile", sysQuery.getMobile());
        return JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params));
    }

    @Override
    public AjaxResult marryQuery(SysQuery sysQuery, String orderNo) {
        AjaxResult result = new AjaxResult();
        JSONObject params = new JSONObject();
        String baseReqSn = "RYC" + IdUtils.fastSimpleUUID().substring(0, 13).toUpperCase();
        params.put("req_time", System.currentTimeMillis());
        // 实名认证
        params.put("request_sn", baseReqSn + "JF005");
        params.put("inter_id", "JF005");
        params.put("name", sysQuery.getName());
        params.put("cardNo", sysQuery.getCardNo());
        result.put("smrz", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 个人诉讼
        params.replace("request_sn", baseReqSn + "JF025");
        params.replace("inter_id", "JF025");
        result.put("grss", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));
        // 婚姻
//        params.put("mobile", sysQuery.getMobile());
        params.replace("request_sn", baseReqSn + "JF032");
        params.replace("inter_id", "JF032");
        result.put("hyhy", JSON.parseObject(HttpUtils.sendPost("http://175.178.170.139:8089/jiekou/jufaAndi", params)));

//        SMSUtils.sendReport(sysQuery.getMobile(), "mar", orderNo);

        return result;
    }

    @Override
    public List<Record> getRecords(String mobile, String sign) {
        List<Record> recordList = sysQueryMapper.recordList(mobile, sign);
        // 处理数据
        for (Record record : recordList) {
            if (record.getProductId() == 3) {         // 企业 MK
                String m = record.getMobile();
                String mk = record.getMoreKeyword();
                record.setMoreKeyword(StringUtils.isEmpty(mk) ? m : mk);
            } else {
                record.setMoreKeyword(StringUtils.isEmpty(record.getName()) ? "查询关键字不全" : ("**" + record.getName().substring(1)));
            }
            record.setPayState("SUCCESS".equals(record.getPayState()) ? "-查询完成" : "");
            record.setName(null);
            record.setCardNo(null);
            record.setMobile(null);
        }
        return recordList;
    }

    /**
     * 查询进件记录
     *
     * @param id 进件记录主键
     * @return 进件记录
     */
    @Override
    public SysQuery selectSysQueryById(Long id) {
        return sysQueryMapper.selectSysQueryById(id);
    }

    /**
     * 查询进件记录列表
     *
     * @param sysQuery 进件记录
     * @return 进件记录
     */
    @Override
    public List<SysQuery> selectSysQueryList(SysQuery sysQuery) {
        return sysQueryMapper.selectSysQueryList(sysQuery);
    }

    /**
     * 新增进件记录
     *
     * @param sysQuery 进件记录
     * @return 结果
     */
    @Override
    public int insertSysQuery(SysQuery sysQuery) {
        return sysQueryMapper.insertSysQuery(sysQuery);
    }

    /**
     * 修改进件记录
     *
     * @param sysQuery 进件记录
     * @return 结果
     */
    @Override
    public int updateSysQuery(SysQuery sysQuery) {
        sysQuery.setUpdateTime(DateUtils.getNowDate());
        return sysQueryMapper.updateSysQuery(sysQuery);
    }

}
